#!/usr/bin/python
# coding:utf-8

import pymysql
from DBUtils.PooledDB import PooledDB
from contextlib import contextmanager

# 数据库连接池
pool = None


def init_app(app):
    global pool
    if pool is None:
        config = {
            'host': app.config.get('MYSQL_HOST'),
            'port': int(app.config.get('MYSQL_PORT')),
            'user': app.config.get('MYSQL_USER'),
            'password': app.config.get('MYSQL_PWD'),
            'db': app.config.get('MYSQL_DB'),
            'charset': 'utf8',
            'cursorclass': pymysql.cursors.DictCursor
        }
        pool = PooledDB(pymysql, **config)


@contextmanager
def create_cursor():
    conn = pool.connection()
    cursor = conn.cursor()
    try:
        yield conn, cursor
    finally:
        cursor.close()
        conn.close()


